#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>

#include "lcd.h"
#include "seri.h"

/**
	@brief 检测可燃气体的浓度
**/
void *detect_smoke(void *arg)
{
	//把接可燃气体传感器的串口打开
	int fd,ret,fd_seri,i;
	//把beep打开
	int beep_fd;
 	//发送给传感器的命令
	char cmd[] = {0xFF,0x01,0x86,0,0,0,0,0,0x79};
	int flag = 0; //假设beep的初始状态是关闭的	
	char rcv[9];
	//fd_seri 代表 已经打开的： /dev/ttySAC1 设备
	if((fd_seri=open_port(fd_seri,1))<0){
		perror("open_port error");
		return NULL;
	}
	if((i=set_opt(fd_seri,9600,8,'N',1))<0){
		perror("set_opt error");
		return NULL;
	}
	beep_fd = open("/dev/beep", O_RDWR);
	while (1)
	{
		write(fd_seri, cmd, sizeof(cmd));		
		//读取传感器回复的指令
		ret = read(fd, rcv, sizeof(rcv));
		if ((ret != 9) && (rcv[0] != 0xFF))
			continue;
		
		 //解析传感器回复的指令 计算出可燃气体的浓度值
		 int value;
		 value = rcv[2]<<8 | rcv[3];
		 
		 //超标
		 if ((value >= 0x0100) && (flag == 0))
		 {
			 //打开beep
			// beep_ctrl(beep_fd, 1);
			 flag = 1;
		 }
		 else if (flag == 1)
		 {
			//beep_ctrl(beep_fd, 0);
			flag = 0;
		 }
		 usleep(200000);
		
	} 
	close(fd_seri);
}

/**
	@brief 检测当前的温度、湿度、大气压力、光照强度
**/
void *detect_env(void *arg)
{
	int fd,i;
	int light_state = 0;
	int web,shidu,qiya;
	//fd_seri 代表 已经打开的： /dev/ttySAC2 设备
	if((fd=open_port(fd,2))<0){
		perror("open_port error");
		return NULL;
	}
	if((i=set_opt(fd,9600,8,'N',1))<0){
		perror("set_opt error");
		return NULL;
	}
	
	while (1)
	{
		char cmd[] = {0xA5, 0x83, 0x28};
		write(fd, cmd, sizeof(cmd));
		
		char rcv[24];
		int  ret;
		ret = read(fd, rcv, sizeof(rcv));
		if ((ret != 24) && (rcv[0]!=0x5A) && (rcv[1]!=0x5A))
		{
			usleep(200000);
			continue;
		}
		//	0x5a 0x5A 0x15 0x04 0x00 0x00 0x01 0x02 0x0b 0x5a 0x5A 0x45 0x0a 十个字节 0x0a
		int n;
		//for (n = 0; n < ret; n++)
		//	printf("%x ", rcv[n]);
		//printf("\n");
		
		int lux;
		lux = rcv[4]<<24|rcv[5]<<16|rcv[6]<<8|rcv[7];
		
		//根据光照强度的值 自动控制灯光的亮和灭
		if ((lux < 50) && (light_state == 0))
		{
			//开灯 显示light_on.bmp
			lcd_draw_bmp("light_on.bmp", 144, 240,350, 190);
			light_state = 1;
		}
		else if (light_state == 1)
		{
			//关灯 显示light_off.bmp
			lcd_draw_bmp("light_off.bmp", 144, 240,350, 190);
			light_state = 0;
		}
		
		int haiba;
		
		web = ((rcv[13]<<8) | rcv[14])/100;
		//printf("wendu: %d\n", web);
		lcd_draw_rect(680,190, 100, 20,0xffffffff);
		lcd_draw_digit(web,680, 190, RED);
		
		//lcd_draw_bmp("atmos.bmp", 586, 380, 100, 80);
		qiya = ((rcv[15]<<14)|(rcv[16]<<16)|(rcv[17]<<8)|rcv[18])/10000;
		//printf("qiya: %d\n", qiya);
		lcd_draw_rect(700,410, 100, 20,0xffffffff);
		lcd_draw_digit(qiya,700, 410, RED);
		 	
		shidu = ((rcv[19]<<8)|rcv[20])/100;
		//printf("shidu: %d\n", shidu);
		lcd_draw_rect(680,290, 100, 20,0xffffffff);
		lcd_draw_digit(shidu, 680, 290, RED);
		
		usleep(200000);
	}
	close(fd);
}

